package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.ReaderDAO;
import mwa.cs.dao.RouteDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.UserLoginDAO;
import mwa.cs.dao.WaterChargeDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Route;
import mwa.cs.model.WaterCharge;
import mwa.cs.util.Encryption;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS12002Srvl
 */
public class CS12005Srvl extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private Database db;
	private String vaAgentBrowser;
	private String vaUrlAddress;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	
	public CS12005Srvl() {
		super();
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		String vaProcessType = "";

		try {
			vaProcessType = request.getParameter("process_type");
		} catch (Exception ex) {
			
		}

		if (vaProcessType.equals("changePassword")) 
			changePassword(request, response);
		else if (vaProcessType.equals("db")) 
			getDbStatus(request, response);

	}
	
	public void changePassword(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		String vaOldPass = request.getParameter("oldPass");
		String vaNewPass = request.getParameter("newPass");
		String vaConfirmPass = request.getParameter("confirmPass");
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			response.getWriter().write("connect_db_fail");
		}
		
		UserLoginDAO vaUserLoginDAO = new UserLoginDAO(db);
		
		// select UserID in DB
		String vaUserPasswordOld = vaUserLoginDAO.findUserPasswordByUserId(vnUserId);
		
		if(vaUserPasswordOld == null)
		{
			db.close();
			response.getWriter().write("no_user");
		}
		else
		{
			Encryption voEncryp = new Encryption();
			
			String vaOldPasswordMd5 = voEncryp.md5Encrypt(voEncryp.dataEncrypt(vaOldPass));
			
			if(!vaUserPasswordOld.equals(vaOldPasswordMd5))
			{
				db.close();
				response.getWriter().write("old_pass_no_match");
			}
			else
			{
				String vaNewPasswordMd5 = voEncryp.md5Encrypt(voEncryp.dataEncrypt(vaNewPass));
				boolean vbResult = false;
				try {
					db.beginTransaction();
					vbResult = vaUserLoginDAO.updateUserPasswordByUserId(vnUserId, vaNewPasswordMd5);
					db.commit();
				} catch (Exception e) {
					SMErrorLogDAO.getInstance().addLog(0, "CS12005", JDate.getDate(), JDate.getTime(),vnUserId, "CS12005Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
					db.rollback();
					e.getMessage();
				}
				
				db.close();
				
				if(vbResult)
					response.getWriter().write("success");
				else
					response.getWriter().write("fail");	
			}
		}
	}

	public void getDbStatus(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		PrintWriter voOut = response.getWriter();
		try {
			this.db = new Database();
			db.close();
			voOut.print("success");
		} catch (Exception ex) {
			db.close();
			voOut.print("connect_db_fail");
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
